package capstone.android.application.nalg.helpers;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;

import com.google.gson.Gson;

public class ConnectionManager {

	public static Gson gson = new Gson();
	public ConnectionManager(){
		
	}
	public static String sendToDb(final String URL, final String userId, final Context context) {
		String json = "";
		HttpClient client = new DefaultHttpClient();
		HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
		try {
			String url = URL + "/profile/" + userId;
			HttpGet get = new HttpGet(url);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			json = client.execute(get, responseHandler);
		} catch (Exception e) {
			
		}
		
		return json;
	}
	public static String sendJson(final String URL, final String jsonProfile, final Context context) {
		String json = "";
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
        HttpResponse response;
        try {
            HttpPost post = new HttpPost(URL);
            StringEntity se = new StringEntity(jsonProfile);  
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(se);
            response = client.execute(post);
//                    Toast.makeText(getApplicationContext(), "Profile Successfully Synchronized", Toast.LENGTH_SHORT);

            /*Checking response */
            if(response!=null){
            	BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            	StringBuilder builder = new StringBuilder();
            	for (String line = null; (line = reader.readLine()) != null;) 
            	    builder.append(line).append("\n");
          
            	json = builder.toString();
            }

        } catch(Exception e) {
            e.printStackTrace();
        }
   
        return json;
	}
}
